package com.lanou3g.code0418.control;

import java.util.concurrent.RecursiveTask;

/**
 * Created by dllo on 18/4/18.
 */
public class SumTask extends RecursiveTask<Long> { //RecursiveTask会帮你开线程
    private Long target;
    private Long from;

    //阈值 如果from和target的差 > 该值,则 拆分任务
    private static final long THRESHOLD = 100000;

    public SumTask(Long from, Long target) {
        this.target = target;
        this.from = from;
    }

    @Override
    protected Long compute() {
        if (target - from <= THRESHOLD) {
            //任务已经足够小了,自己计算完成即可

            long sum = 0L;

            for (Long i = from; i <= target; i++) {
                sum += i;
            }
            return sum;
        }
        //任务还是很大,需要拆分

        //计算前一半的值
        SumTask sumTask1 = new SumTask(from, (target + from) / 2);

        //计算后一半的值
        SumTask sumTask2 = new SumTask((target + from) / 2 + 1, target);

        invokeAll(sumTask1, sumTask2);
        //关键代码,invokeAll分配任务时自身也做四分之一,分配出去的任务也是再分配时
        //分配者也是自身有任务在分出去
        //而若是sumTask1.fork();  sumTask2.fork(); 分配任务时,分配者本身没任务做
        //全部分配下去,因此其效率很低


        return sumTask1.join() + sumTask2.join();
    }

}
